package com.nxy.test.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by snailnan on 2017/2/22.
 */
public class NioServerThread implements Runnable{
    private SocketChannel sc;
    private ByteBuffer writeBuffer =  ByteBuffer.wrap("nxy".getBytes());
    private ByteBuffer readBuffer = ByteBuffer.allocate(20);
    public static final  byte SPLIT = 47; // 分隔符"/"

    public NioServerThread(SocketChannel s){
        this.sc = s;
    }

    public void run() {
        try {
            handleService();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void handleService() throws IOException {
        sc.configureBlocking(false);
        int size = sc.read(readBuffer);
        while (size != -1){
            readBuffer.flip();
            while (readBuffer.hasRemaining()){
                int b = readBuffer.get();
                if (b == SPLIT){
                    System.out.println();
                    System.out.println("service read finish");
                    sc.write(writeBuffer);
                }else {
                    System.out.print((char) b);
                }
            }
            readBuffer.clear();
            size = sc.read(readBuffer);
        }
//        sc.finishConnect();
    }
}
